import React, { useEffect, useRef, useState } from 'react'
import { View, Text, ScrollView, StyleSheet } from 'react-native'
import { LayoutType, ColorBg, OffsetType } from "./types"
type Props = {
  defaultIndex?: number
  autoplay?: number | boolean,//默认为false true的时候为2000ms
  loop?: boolean
  children?: any,
}
const Swiper = ({ children, loop = true, defaultIndex = 0, autoplay = true, ...rest }: Props) => {

  const defaultProps = {
    horizontal: true,// 是否是水平方向 排列默认false
    pagingEnabled: true,// 是否成视图的倍数滚动 默认false  horizontal:false时pagingEnabled在 Android 上不支持
    showsHorizontalScrollIndicator: false,// 是否显示水平方向的滚动条
    showsVerticalScrollIndicator: false,// 是否显示垂直方向的滚动条
    bounces: false,//ios 末尾是否可以弹性地拉动一截
    scrollsToTop: false,//ios 点击状态栏的时候视图会滚动到顶部。默认值为 true
    removeClippedSubviews: false,
    automaticallyAdjustContentInsets: false,
  }
  const total: number = Object.keys(children).length
  const [index, setIndex] = useState(0)
  // 载体宽高
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)
  // 初始滚动位置
  const [offset, setOffset] = useState<OffsetType>({ x: 0, y: 0 })
  // 起始位置备份 这个是用来记录当前scroll移动到哪儿了的 
  const [internals, setInternals] = useState<OffsetType>({ x: 0, y: 0 })
  // ScrollViewref
  const refScrollView = useRef<any>(null)
  // autoplayRef
  const autoplayTimer = useRef<any>(null)
  const onLayout = (e: any) => {
    const { width, height } = e.nativeEvent.layout
    setWidth(width)
    setHeight(height)
    if (loop) {
      // loop的时候设置默认值
      setOffset({ ...offset, ...{ x: width } })
      setInternals({ ...internals, ...{ x: width } })
    }
  }
  const loopJump = (num: number, offset: OffsetType) => {
    const scrollView: any = refScrollView.current
    const loopJumpTimer = setTimeout(() => {
      if (scrollView.setPageWithoutAnimation) {
        scrollView.setPageWithoutAnimation(num + 1)
      } else {
        if (num === 0) {
          scrollView.scrollTo({
            ...offset,
            animated: false
          })
        } else if (num === total - 1) {
          scrollView.scrollTo({
            ...offset,
            animated: false
          })
        }

      }
      clearTimeout(loopJumpTimer)
    }, scrollView.setPageWithoutAnimation ? 50 : 300)
  }
  const scrollBy = (step: number) => {
    const scrollView: any = refScrollView.current
    const diff = step + index + (loop ? 1 : 0)
    const x = diff * width
    scrollView && scrollView.scrollTo({ x, animated: true })
  }
  const autoplayFunc = () => {
    const autoplayTime = typeof autoplay === 'boolean' ? 2000 : autoplay
    autoplayTimer.current && clearTimeout(autoplayTimer.current)
    // 我是用index来操控的
    autoplayTimer.current = setTimeout(() => {
      if (index < total + 1) {
        // 移动几个
        scrollBy(1)
      }
    }, autoplayTime)
  }
  /**
   * index相当的重要，获取方式再斟酌一下
   * @param offset 偏移量
   */
  const updateIndex = (offset: OffsetType, cb?: Function) => {
    // Android ScrollView will not scrollTo certain offset when props change
    let _index = index
    const step = width
    const diff = offset.x - internals.x
    _index = _index + Math.round(diff / step)
    // 循环播放
    if (loop) {
      if (_index <= -1) {
        _index = total - 1
        offset.x = step * total
        loopJump(_index, offset)
      } else if (_index >= total) {
        _index = 0
        offset.x = step
        loopJump(_index, offset)
      }
    }
    setOffset({ ...offset })
    setInternals({ ...offset })
    setIndex(_index)
  }
  // 用width结合useEffect 模拟元素加载完成的生命周期
  useEffect(() => {
    if (width !== 0) {
      autoplay && autoplayFunc()
    }
  }, [width])
  // 监听改变 因为state是一个异步 autoplay专用
  useEffect(() => {
    if (width !== 0 && autoplay) {
      autoplayFunc()
    }
  }, [index])
  // 开始拖动
  const onScrollBegin = (e: any) => {
    if (!e.nativeEvent.contentOffset) {
      e.nativeEvent.contentOffset = {
        x: e.nativeEvent.position * width
      }
    }
    if (internals.x === 0) {
      setInternals({ ...e.nativeEvent.contentOffset })
    }

  }
  const onScrollEnd = (e: any) => {
    if (!e.nativeEvent.contentOffset) {
      e.nativeEvent.contentOffset = {
        x: e.nativeEvent.position * width
      }
    }
    updateIndex(e.nativeEvent.contentOffset)
  }

  const renderScrollView = () => {
    const pages = Object.keys(children)

    if (loop) {
      pages.unshift(`${total - 1}`)
      pages.push('0')
    }
    return (
      <ScrollView
        ref={refScrollView}
        {...defaultProps}
        contentOffset={offset}
        onScrollBeginDrag={onScrollBegin}
        onMomentumScrollEnd={onScrollEnd}
      >
        {pages.map((item, i) => {
          return <View key={i} style={[{ width: width, backgroundColor: ColorBg[i] }]}>
            {children[item]}
          </View>
        })}
      </ScrollView>
    )
  }
  return (
    <View style={styles.swiper} onLayout={onLayout}>
      {renderScrollView()}
    </View>
  )
}
const styles = StyleSheet.create({
  swiper: {
    flex: 1,
    position: 'relative',
    backgroundColor: "#648e93"
  },
  swiper_item: {
    backgroundColor: "#f1939c"
  }
})
export default Swiper